<template>
    <div>
        <div>
            <el-row class="custom-title m-t-20 m-b-20">
                <h3>新股发行基本信息
                    <span class="m-l-20">最后更新时间：{{eventDto.modifyTime | cmsMoment}}</span>
                    <el-button type="primary" size="medium" class="m-l-20 pull-right" @click="save" round>保存</el-button>
                </h3>
            </el-row>
            <el-form label-width="90px" class="custom-box p-20" :rules="rules" ref="eventDto" :model="eventDto">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="中文标题" prop="title">
                            <el-autocomplete
                              class="w-100"
                              :maxlength="200"
                              v-model="eventDto.title"
                              :fetch-suggestions="getSearchTitle"
                              placeholder="请输入内容"
                              :trigger-on-focus="false"
                              @select="handleSelect"
                            ></el-autocomplete>
                        </el-form-item>
                        <el-form-item label="标的企业" required>
                            <el-row>
                                <el-col :span="18">
                                  <el-tooltip class="item" effect="dark" :content="companyText" placement="top">
                                    <el-button @click="companyLibrary" class="company-detail">{{companyText}}</el-button>
                                  </el-tooltip>
                                </el-col>
                                <el-col :span="5" :offset="1">
                                    <el-button type="primary" @click="toDetail" :disabled="companyText=='企业库'">查看详情</el-button>
                                </el-col>
                            </el-row>
                        </el-form-item>
                        <el-form-item label="交易所">
                            <el-select class="w-100" placeholder="请选择" v-model="comIpoVO" value-key="id" @change="getStockCode">
                                <el-option v-for="(item,index) in comIpoVOList" :key="index" :label="getExchangeName(item.exchangeId)" :value="item" :id="item.id">{{item.exchangeId|getDicNameById('exchangeType')}}</el-option>                                
                            </el-select>
                        </el-form-item>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="股票代码">
                                    <el-input v-model="stockCode" disabled></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="股票发行价">
                                    <el-input type="number" v-model="eventDto.issuePrice">
                                      <template slot="append">万</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="上市申请日" prop="startTime" class="line-h-20">
                                    <el-date-picker v-model="eventDto.startTime" class="w-100" type="date" placeholder="选择日期"></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="上市日">
                                    <el-date-picker v-model="eventDto.endTime" class="w-100" type="date" placeholder="选择日期"></el-date-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                              <el-form-item label="上市事件类型" class="line-h-20" prop="ipoType">
                                  <el-select placeholder="请选择" v-model="eventDto.ipoType">
                                      <el-option v-for="(item,index) in initView.ipoType" :key="index" :value="item.dictValue-0" :label="item.dictName"></el-option>                                                  
                                  </el-select>
                              </el-form-item>
                            </el-col>
                            <el-col :span="12">
                            <el-form-item label="是否发行成功" class="line-h-20" prop="tradeStatus">
                                <el-select placeholder="请选择" v-model="eventDto.tradeStatus">
                                  <el-option label="进行中" :value="1"></el-option>
                                  <el-option label="已失败" :value="2"></el-option>
                                  <el-option label="已完成" :value="3"></el-option>
                                </el-select>
                            </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                            <el-form-item label="上市首日收盘价" class="line-h-20">
                                <el-input type="number" v-model="eventDto.ipoFirstrate">
                                    <template slot="append">万</template>
                                </el-input>
                            </el-form-item>
                            </el-col>
                            <el-col :span="12">
                            <el-form-item label="币种">
                                <el-select v-model="eventDto.currencyType">
                                  <el-option v-for="(item,index) in initView.currencyType" :key="index" :label="item.dictName" :value="item.dictValue-0"></el-option>
                                </el-select>
                            </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="募集资金总额" class="line-h-20">
                                    <el-input type="number" v-model="eventDto.ipoRaisTotal">
                                        <template slot="append">万</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="募集资金净额" class="line-h-20">
                                    <el-input type="number" v-model="eventDto.ipoRaisNet">
                                        <template slot="append">万</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="总实际股权" prop="totalStockRate">
                                    <el-input type="number" v-model="eventDto.totalStockRate">
                                        <template slot="append">%</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="股票发行数目" class="line-h-20">
                                    <el-input type="number" v-model="eventDto.sharesCount"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="CV行业分类" class="line-h-20">
                          <el-cascader
                            disabled
                            class="w-100"
                            v-model="cvIndustryValue"
                            :options="cvIndustryListCascader"/>
                        </el-form-item>
                        <el-form-item label="国标分类">
                          <el-cascader
                            disabled
                            class="w-100"                          
                            v-model="csIndustryValue"
                            :options="csIndustryListCascader"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" :offset="1">
                      <el-form-item label="证监会分类" class="line-h-20">
                          <el-cascader
                            disabled
                            class="w-100"
                            v-model="sfcIndustryValue"
                            :options="sfcIndustryListCascader"/>
                        </el-form-item>
                        <el-form-item label="申银万国">
                          <el-cascader
                            disabled
                            class="w-100"
                            v-model="snIndustryValue"
                            :options="snIndustryListCascader"/>
                        </el-form-item>
                        <el-form-item label-width="90px" label="标签">
                            <el-row class="custom-box h-scroll">
                                <el-tag v-for="(item,index) in companyDetailsVO.tagList" :key="index" :type="item.operateType==1?'':'info'" class="m-l-5">{{item.tagName}}</el-tag>
                            </el-row>
                        </el-form-item>
                        <el-form-item label="交易描述" prop="description">
                            <el-input type="textarea" :rows="4" :maxlength="2000" v-model="eventDto.description"></el-input>
                        </el-form-item>
                        <el-form-item label="备注">
                            <el-input type="textarea" :rows="4" :maxlength="2000" v-model="eventDto.remark"></el-input>
                        </el-form-item>
                        <el-form-item label="信息来源" required>
                          <el-row v-for="(item,index) in eventInfoDtos" :key="index">
                            <el-col :span="16">
                              <a :href="item.infoFromUrl" target="_blank" class="aCss">{{item.infoFrom}}</a>
                            </el-col>
                            <el-col :span="8">
                              <button type="button" class="custom-btn custom-btn-round">
                                  <i v-if="index!=0" class="fa fa-close" @click="delInfoVos(index)"></i>
                                  <i v-if="index==0" class="fa fa-plus" @click="addInfoVos"></i>                                    
                              </button>
                              <el-button type="primary" @click="infoSrcPopUp(index)">编辑详情</el-button>
                            </el-col>
                          </el-row>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <!-- 信息来源弹窗 -->
            <el-dialog title="信息来源" :visible.sync="infoSrcPopUpFlag">
                <el-form label-width="130px" :model="eventInfoDto" :rules="rulesInfoSrcPopUp" ref="infoSrcPopUp">
                    <el-row>
                      <el-col :span="16">
                        <el-form-item label="信息发生时间" prop="happenTime">
                            <el-date-picker v-model="eventInfoDto.happenTime" placeholder="其请选择日期"></el-date-picker>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                          <el-form-item label="媒体类型" label-width="70px">
                              <el-select v-model="eventInfoDto.mediaType">
                                <el-option label="新闻" :value="1"></el-option>
                                <el-option label="报告" :value="2"></el-option>
                              </el-select>
                          </el-form-item>
                      </el-col>
                    </el-row>
                    <el-form-item label="信息来源媒体" prop="infoFrom">
                        <el-input v-model="eventInfoDto.infoFrom"></el-input>
                    </el-form-item>
                    <el-form-item label="信息来源url" prop="infoFromUrl">
                        <el-input v-model="eventInfoDto.infoFromUrl"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="infoSrcPopUpSure">确 定</el-button>
                    <el-button @click="infoSrcPopUpFlag = false">取 消</el-button>
                </span>
            </el-dialog>
            <!-- 企业库弹窗 -->
            <CompanyInfo
              :companyDetailDialog="companyDetailDialog"
              @closeCompanyDialog="closeCompanyDialog"
              @getName="getName">
            </CompanyInfo>
        </div>
        <div>
            <DistributionCost :eventId="eventId" ref="cost"></DistributionCost>
        </div>
    </div>
</template>
<script lang="ts">
import Vue from 'vue';
import { getCascaderData } from '../../../../libs/utils';
import { Component, Watch } from 'vue-property-decorator';
import DistributionCost from './distribution-cost.vue';
import CompanyInfo from '../../../../components/company-info/index.vue';
import ServiceEvent from '../../../../service/event/index';
import CompanyService from '../../../../service/subject/company/basic-info';
import { StateMessage } from '../../../../service/common/interface';
// import ServiceComIpoController from '../../../../service/subject/company/listed-info/index';
import { ComIpoVO, EventDto, EventInfoVo, EventInfoDto, EventDetailsVo, CompanyDetailsDto, EventTitleVO, CompanyDetailsVO } from '../../../../api/Interface';
interface CompanyOpenSearchDto {
    searchType: string;
    name: string;
    // attribute: number;
}
interface Result {
    value: string;
    id: number;
}

@Component({
  components: { 
      DistributionCost,
      CompanyInfo
   }
})
export default class CompanyList extends Vue {
    // refs
    public $refs: {
      eventDto: HTMLFormElement;
      infoSrcPopUp: HTMLFormElement;
      cost: HTMLFormElement;
    };

    // 初始化数据 相当于data
    public eventInfoVo: EventInfoVo = {} as EventInfoVo; // 信息来源
    public comIpoVOList: Array<ComIpoVO> = []; // 交易所列表，带出股票代码
    public comIpoVO: ComIpoVO = {exchangeId: ''} as ComIpoVO; // 选中的交易所
    public stockCode: string = ''; // 股票代码
    public eventDto: EventDto = {} as EventDto; // 事件详情
    public companyDetailsVO: CompanyDetailsVO = {} as CompanyDetailsVO; // 获取企业库关联详细信息
    public result: Array<Result> = []; // 模糊查询结果callBack参数
    public eventDetailsVo: EventDetailsVo = {} as EventDetailsVo;
    public infoSrcPopUpFlag: boolean = false; // 信息来源弹窗flag
    public companyDetailDialog: boolean = false; // 企业库弹窗flag
    public companyOpenSearchDto: CompanyOpenSearchDto = {} as CompanyOpenSearchDto; // 企业库搜索
    public companyData: Array<CompanyDetailsDto> = []; // 企业库搜索列表
    public eventInfoDto: EventInfoDto = {} as EventInfoDto; // 信息来源详情
    public eventInfoDtos: Array<EventInfoDto> = [{
        eventId: 0,         //事件id
        infoFromUrl: '',         //信息来源媒体URL
        mediaType: 1,         //媒体类型 1新闻、2报告
        id: 0,         //null
        infoFrom: '',         //信息来源媒体
        happenTime: ''         //发生时间
    }]; // 信息来源列表
    public titleSearchList: Array<EventTitleVO> = [];
    // 标的企业
    public companyId: string = '';
    public companyText: string = '企业库';
    public infoSrcNum: number = 0;
    public eventId: number = 0; // 发行费用eventId
    // cv行业
    public cvIndustryList = this.$store.state.user.dictionary.cvIndustryList;
    public cvIndustryListCascader = getCascaderData( {data: this.cvIndustryList} );
    public cvIndustryValue: string[] = [];
    // 国标
    public csIndustryList = this.$store.state.user.dictionary.csIndustryList;
    public csIndustryListCascader = getCascaderData( {data: this.csIndustryList} );
    public csIndustryValue: string[] = [];
    // 证监会
    public sfcIndustryList = this.$store.state.user.dictionary.sfcIndustryList;
    public sfcIndustryListCascader = getCascaderData( {data: this.sfcIndustryList} );
    public sfcIndustryValue: string[] = [];
    // 申银万国
    public snIndustryList = this.$store.state.user.dictionary.snIndustryList;
    public snIndustryListCascader = getCascaderData( {data: this.snIndustryList} );
    public snIndustryValue: string[] = [];
    // 基本信息验证规则
    public rules = {
      title: [{ required: true, message: '请输入中文标题', trigger: 'blur' }],
      startTime: [{ required: true, message: '请选择上市申请日', trigger: 'blur' }],
      ipoType: [{ required: true, message: '请选择上市事件类型', trigger: 'blur' }],
      tradeStatus: [{ required: true, message: '请选择是否发行成功', trigger: 'blur' }],
      description: [{ required: true, message: '请输入交易描述', trigger: 'blur' }],
      stockCode: [{ validator: this.stockCodeCheck, trigger: 'blur' }], // 股票代码
      totalStockRate: [{ validator: this.percentageCheck, trigger: 'blur' }], // 总实际股权
    };
    // 信息来源验证规则
    public rulesInfoSrcPopUp = {
      happenTime: [{ required: true, message: '请选择信息发生时间', trigger: 'blur' }],
      infoFromUrl: [{ validator: this.infoFromUrlCheck, trigger: 'blur' }],
      infoFrom: [{ required: true, message: '请输入信息来源媒体', trigger: 'blur' }],
    };
    public initView = {
      ipoType: this.$store.state.user.dictionary.dicList.ipoType, // 上市类型
      exchangeType: this.$store.state.user.dictionary.dicList.exchangeType, // 交易所
      currencyType: this.$store.state.user.dictionary.dicList.currencyType, // 币种
      openSearchNameType: this.$store.state.user.dictionary.dicList.openSearchNameType, // 企业库搜索弹窗下拉
    };

    // watch
    @Watch('msg')
    public onChildChanged(val: string, oldVal: string) {
        return val + '***';
    }

    // 声明周期钩子
    public mounted() {
      if (this.$route.params.eventId !== '-1') {
        this.getEventDetailById(this.$route.params.eventId);
      }
    }

    // 交易所过滤器
    public getExchangeName(exchangeId: string): string {
      let name: string = '';
      for (const item of this.initView.exchangeType) {
        if (exchangeId === item.dictValue) {
          name = item.dictName;
          break;
        }
      }
      return name;
    }
    // 保存按钮
    public save(info: StateMessage) {
      this.eventDto.infoStatus = '0000';
      if (info.infoStatus) {
          this.eventDto.infoStatus = info.infoStatus;
          this.eventDto.publishMessage = info.publishMessage;
      }
      this.eventDto.eventType = 16; // 事件分类  17 融资事件 16 新股发行      
      this.eventDto.eventInfos = this.eventInfoDtos; // 信息来源
      if (this.comIpoVO.exchangeId) {
          this.eventDto.exchangeId = Number(this.comIpoVO.exchangeId); // 交易所id      
      }
      this.$refs.eventDto.validate(async (valid: boolean) => {
          if (valid) {
              if (this.$route.params.eventId !== '-1') {
                if (this.checkInfoSrc()) {
                    this.$message.warning('请填完整的信息来源');          
                } else {
                    this.updateEvent();
                }
              } else {
                  if (this.companyText === '企业库') {
                      this.$message.warning('请选择企业库');
                  } else if (this.checkInfoSrc()) {
                      this.$message.warning('请填完整的信息来源');          
                  } else {
                      this.addSaveEvent();
                  }
              }
          }
      });
    }
    // 验证信息来源必填且每一项都完整
    public checkInfoSrc(): boolean {
      let flag = false;
      this.eventInfoDtos.map((item: EventInfoDto) => {
        if (!item.infoFrom) {
            flag = true;
        }
      });
      return flag;
    }
    // 模糊查询带出详情 
    public handleSelect(item: Result) {
      this.$router.replace({ name: 'new-issue-edit', params: { eventId: item.id.toString(), tabIndex: '0'}});      
      this.getEventDetailById(item.id.toString());
      this.$refs.cost.getCostInfoById();
    }
    // 根据Id获取事件信息
    public async getEventDetailById(id: string) {
      const { resCode, data} = await ServiceEvent.getEventDetail(id);
      if (resCode === '0') {
        this.eventDto = data;
        this.eventInfoDtos = data.eventInfos;
        this.eventId = data.id; // 事件id
        this.companyText = data.companyName === null ? '企业库' : data.companyName;
        this.companyId = data.companyId;
        // 获取标的企业信息
        this.getCompanyInfo();
        this.getComIpoByid();
        // this.comIpoVO.exchangeId = data.exchangeId.toString(); // 交易所ID
        this.$emit('changeInfo', data.infoStatus);
      }
    }
    // 根据当前企业/工商id查询上市交易所信息
    public async getComIpoByid() {
      const data = await ServiceEvent.getComIpo(this.companyId);
      this.comIpoVOList = data;
      // 根据交易所ID反显股票代码
      if (this.eventDto.exchangeId) {
        data.map((item: ComIpoVO) => {
          if (this.eventDto.exchangeId.toString() === item.exchangeId) {
            this.stockCode = item.stockCode;
            this.comIpoVO = item;
          }
        });
      }
    }
    // 选中交易所带出股票代码
    public getStockCode(item: ComIpoVO) {
      this.stockCode = item.stockCode;
    }
    // 修改事件基本信息
    public async updateEvent() {   
      const { resCode } = await ServiceEvent.updateEvent(this.eventDto);
      if (resCode === '0') {
        this.$message.success('修改成功！');
        this.$emit('saveSuccess', true);        
      }
    }
    // 添加事件基本信息
    public async addSaveEvent() {
      const { resCode, data } = await ServiceEvent.addSaveEvent(this.eventDto);
      if (resCode === '0') {
        this.$message.success('添加成功！');
        this.$emit('saveSuccess', true);
        this.eventId = data;
        this.$router.replace({ name: 'new-issue-edit', params: { eventId: this.eventId.toString(), tabIndex: '0'}});
      }
    }

    // 企业库按钮
    public companyLibrary() {
      this.companyDetailDialog = true;
    }
    // 企业库搜索按钮
    public getCompanyDetail() {
      this.companyDetailDialog = true; // 临时
    }
    // 关闭企业信息弹出框
    public closeCompanyDialog() {
        this.companyDetailDialog = false;
    }
    // 获取企业名称
    public getName(company: {id: number, name: string}) {
        this.eventDto.companyId =  company.id;
        this.eventDto.companyName = company.name;
        this.companyText = company.name;
        this.companyId = company.id.toString();
        this.getCompanyInfo();
        this.getComIpoByid();
    }
    // 标的企业信息
    public async getCompanyInfo() {
        const {resCode, data} = await CompanyService.getCompanyById(Number(this.companyId));
        if (resCode === '0') {
            this.companyDetailsVO = data;
            // 回显行业
            data.industryList.map( (item) => {
                switch (item.industryType) {
                    case 1:
                        this.cvIndustryValue = this.cvIndustryValue.concat(item.oneLevel, item.twoLevel, item.threeLevel);
                        break;
                    case 2:
                        this.csIndustryValue = this.csIndustryValue.concat(item.oneLevel, item.twoLevel, item.threeLevel);
                        break;
                    case 3:
                        this.sfcIndustryValue = this.sfcIndustryValue.concat(item.oneLevel, item.twoLevel, item.threeLevel);
                        break;
                    case 4:
                        this.snIndustryValue = this.snIndustryValue.concat(item.oneLevel, item.twoLevel, item.threeLevel);
                        break;
                    default:
                        break;
                }
            });
        }
    }
    // 查看详情按钮
    public toDetail() {
      this.$router.push({name: 'company-detail', params: {itemId: this.companyId}});
    }
    // 中文名称模糊查询
    public async getSearchTitle(queryString: string, cb: any) {
        const res = await ServiceEvent.getSearchTitle({title: this.eventDto.title, eventType: 16});
        if (res.resCode === '0') {
          this.titleSearchList = res.data;
          this.result = this.titleSearchList.map((item: EventTitleVO) => {
            return { value: item.title, id: item.id };
          });
          cb(this.result);
        }
    }
    // 信息来源“编辑详情”按钮
    public infoSrcPopUp(index: number) {
        this.infoSrcPopUpFlag = true;
        this.eventInfoDto = {...this.eventInfoDtos[index]};
        this.infoSrcNum = index;
    }
    // 信息来源编辑弹窗确认按钮
    public infoSrcPopUpSure() {
      this.$refs.infoSrcPopUp.validate(async (valid: boolean) => {
          if (valid) {
              this.$set(this.eventInfoDtos, this.infoSrcNum, this.eventInfoDto);
              this.infoSrcPopUpFlag = false;
          }
      });
      
    }
    // 信息来源 + 号按钮
    public addInfoVos() {
      this.eventInfoDto = {mediaType: 1} as EventInfoDto;
      this.eventInfoDtos.push(this.eventInfoDto);
    }
    // 信息来源 - 号按钮
    public delInfoVos(index: number) {
      this.eventInfoDtos.splice(index, 1);
    }

    /** 自定义验证规则 START */
    // 信息来源URL合法验证
    public infoFromUrlCheck(rule: object, value: string, callback: any) {
      const reg = /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
      if (!value || value === '') {
        callback(new Error('请输入信息来源媒体URL'));
      } else if (!reg.test(value.toLowerCase())) {
        callback(new Error('请输入合法的URL'));
      } else {
        callback();
      }
    }
    // 验证股票代码
    public stockCodeCheck(rule: object, value: string, callback: any) {
      const reg = /^[0-9a-zA-Z]*$/g;
      if (!reg.test(value)) {
        callback(new Error('请输入字母、数字或字母数字组合'));
      } else {
        callback();
      }
    }
    // 百分比数字验证
    public percentageCheck(rule: object, value: number, callback: any) {
      if (value < 0 || value > 100) {
        callback(new Error('请输入100以内的数字'));
      } else {
        callback();
      }
    }
    /** 自定义验证规则 END */
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.w-55{
    width: 55%
}
.w-100{
    width: 100%
}
.h-scroll{
    height: 100px;
    width: 100%;
    overflow-y: auto;
    word-break: break-all;
    word-wrap: break-word;
}
.colorRed{
  color: red;
}
.company-detail {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.aCss {
  color: #409EFF;
  text-align: center;
  text-decoration: underline;
  display: block;
  width: 100%;
  height: 40px;
}
.m-l-20{
  margin-left: 20px;
}
</style>
